package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constrant.MessageConstant;
import com.itheima.constrant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author FCJ
 * @date 2020-01-10 10:07
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    //手机号快速登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse res, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String codeInRedis = jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);
        if (codeInRedis == null) {
            return new Result(false, "验证码已过期，请重新获取");
        }
        String validateCode = (String) map.get("validateCode");
        if (!codeInRedis.equals(validateCode)) {
            return new Result(false, "验证码错误，请重新输入");
        }
//判断当前用户是否为会员
       Member member= memberService.findByTelephone(telephone);
        if (member==null){//不是会员，自动注册会员
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }
//向客户端写入Cookie，内容为手机号
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);
        res.addCookie(cookie);
        //将会员信息保存到Redid
        String json= JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone,60*30,json);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
